package conversation

import (
	"github.com/mitchellh/mapstructure"
	"im_sys/apps/im/ws/internal/svc"
	"im_sys/apps/im/ws/ws_server"
	"im_sys/apps/im/ws/ws_struct"
	"im_sys/apps/task/mq/mq_struct"
	"im_sys/pkg/constants"
	"im_sys/pkg/wuid"
	"time"
)

// Chat 发送方通过websocket发送消息会触发该处理器，将消息封装并通过MqClient.PushMsgToKafka推送到Kafka
func Chat(svc *svc.ServiceContext) ws_server.HandlerFunc {
	return func(server *ws_server.Server, conn *ws_server.WSKeepAlive, message *ws_server.Message) {
		// 解析消息内容，Message中Data的json反序列化后为interface{}，需要将其转换为ws_struct.Chat
		var data ws_struct.Chat
		if err := mapstructure.Decode(message.Data, &data); err != nil {
			_ = server.Send(ws_server.NewErrorMessage(err), conn)
			return
		}

		data.SendId = conn.Uid // 发送方的消息不包含sendId，需要从token中解析获得

		if data.ConversationId == "" {
			data.ConversationId = wuid.CombineId(data.RecvId, data.SendId)
		}

		// 判断当前消息的类型
		switch data.ChatType {
		case constants.SingleChatType:
			// 加入消息队列后，发送方通过调用kafka的Push方法，将消息推入kafka中
			if err := svc.MqClient.PushMsgToKafka(&mq_struct.ChatMsg{
				ConversationId: data.ConversationId,
				ChatType:       data.ChatType,
				SendId:         data.SendId,
				RecvId:         data.RecvId,
				SendTime:       time.Now().Unix(),
				MType:          data.Msg.MType,
				Content:        data.Content,
			}); err != nil {
				_ = server.Send(ws_server.NewErrorMessage(err), conn)
				return
			}

			// 加入消息队列前，发送方直接发送消息给接收方：
			//l := conversation.NewConversation(context.Background(), svc, server)
			//
			//// 处理私聊业务（存储到mongodb）
			//err := l.SingleChat(&data)
			//if err != nil {
			//	_ = server.Send(ws_server.NewErrorMessage(err), conn)
			//	return
			//}
			//
			//// 将消息发送给接收者
			//_ = server.SendByUid(ws_server.NewMessage(data.SendId, ws_struct.Chat{
			//	ConversationId: data.ConversationId,
			//	ChatType:       data.ChatType,
			//	SendId:         data.SendId,
			//	RecvId:         data.RecvId,
			//	Msg:            data.Msg,
			//	SendTime:       time.Now().UnixMilli(),
			//}), data.RecvId)
		default:

		}
	}
}
